#!/usr/bin/env python
#coding:utf-8

import os
import shutil

def sort_files(files):
	keys = [u"微博", u"微信", u"合成", u"纯净", u"APP", u'腾讯', u'teng']
	if 1 == len(files):
		return files[0]

	for key in keys:
		for file in files:
			if key in file:
				return file
#	return files[0]     # 如果没有关键字，就返回第一个
	return None


def calc_files_size(select_files):

	all_size = 0
	for k, v in select_files.items():
		fsize = os.path.getsize(k)
		fsize = fsize/(1024*1024)
		all_size += fsize	#round(fsize,2)

	return  all_size

def get_one_subdir(root_path):
	all_files = os.listdir(root_path)
	sub_dir = []
	for item in all_files:
		if os.path.isdir(root_path+u'/'+item) :
			sub_dir.append(item)
	return sub_dir

def get_all_subfiles(root_path):
	mv_files = []
	for root, dirs, files in os.walk(root_path):
		for item in files:
			# 好奇怪，怎么会有很多是以._开头的重复文件呢？丢弃先
			if '._' == item[:2]:
				continue;
#			if '.mp4' in item:
#				mv_files.append(item)
#			elif '.mov' in item:
#				mv_files.append(item)
			if '.mp4' == item[-4:]:
				mv_files.append(root + u'/' + item)
			elif '.mov' == item[-4:]:
				mv_files.append(root + u'/' + item)

	if 0 != len(mv_files):
		sel_file = sort_files(mv_files)
		if None == sel_file:
			print '======= not keys!!! %s===' % root_path
			sel_file = mv_files[0]

#		sel_file = root_path + u'/' + sel_file
		return sel_file, mv_files

	print '======= not found!!! %s===' % root_path
	return None, None



# 分级获取3层子目录，y/m/d
def get_all_subdir(root_path):

	array_files = []	# 扁平的文件列表（全部视频）
	tree_files = {}		# 树状文件列表（优选视频）
	select_files = {}	# 选中的文件前后的对照表（优选视频）
	dir_y = get_one_subdir(root_path)
	for year in dir_y:
		year_path = root_path + u'/' + year

		month_files = {}
		dir_m = get_one_subdir(year_path)
		for month in dir_m:
			month_path = year_path + u'/' + month


			day_files = {}
			dir_d = get_one_subdir(month_path)
#			if 0 == len(dir_d):
#				continue
			for day in dir_d:
				day_path = month_path + u'/' + day
				selfile, allfile = get_all_subfiles(day_path)
#				print '\t path=[%s], file=[%s]' % (day_path, selfile)

				if None != selfile:
					array_files += allfile
					select_files[selfile] = [year+day[:4], day[4:], selfile[-4:]]

				day_files[day] = selfile

			month_files[month] = day_files

		tree_files[year] = month_files
#	for i in array_files:	print i
#	for k,v in select_files.items():	print 'key=[%s], val=[%s]' % (k,v)
	return select_files

def read_rename_map(file_path):
	rename_dict = []
	with open(file_path, 'r') as f1:
		filelines = f1.xreadlines();

		for line in filelines:
			items = line.split(',')
			if 5 > len(items):
				print '===== file error! %s ======' % line

			#分割日期
			dates = items[0].split('/')
			date = '%s%02d%02d' % (dates[0], int(dates[1]), int(dates[2]))
			items = [unicode(i, 'utf-8') for i in items]
			key_item = {'date': date, 'name': items[1], 'original': items[2], 'singer': items[3], 'school': items[4]}
			song_name = '%s_%s' % (key_item['date'], key_item['name'])
			if key_item['singer'] != '':    song_name += '_%s' % key_item['singer']
			if key_item['school'] != '':    song_name += '_%s' % key_item['school']
			song_name = song_name.replace('/', '+')
			song_name = song_name.replace('\\', '+')
			song_name = song_name.replace('&', '+')
			song_name = song_name.replace('?', ' ')
			key_item['song'] = song_name

#			for k,v in key_item.items():
#				print '%s=%s' % (k,v)

			rename_dict.append(key_item)

		# end for line in filelines
	#end with open(file_path, 'r') as f1:

	return rename_dict

def copy_file(srcfile, dstfile):
	if not os.path.isfile(srcfile):
		print "%s not exist!"% srcfile
	else:
		fpath, fname=os.path.split(dstfile)    #分离文件名和路径
		if not os.path.exists(fpath):
			os.makedirs(fpath)                #创建路径
		shutil.copyfile(srcfile,dstfile)      #复制文件
		print "copy %s -> %s"%( srcfile,dstfile)


path1 = u'e:\\不要音乐MV成片\\2018不要音乐MV成片\\6月\\0615make u feel my love'
path = u'e:/不要音乐MV成片'
path_cp = u'E:/update/'
path2 = u'D:/不要音乐/不要音乐MV成片信息表 - Liang.csv'


if 0:
	sel, all = get_all_subfiles(path1)
	print 'sel=', sel
	for i in all:
		print '\t', i
if 1:
	rename_array = read_rename_map(path2)
	select_files = get_all_subdir(path)

	'''
	all_size = calc_files_size(select_files)
	print all_size/1024, 'G'

	'''
	for k, v in select_files.items():
		finded = False
		for key in rename_array:
			v1 = v[1].lower().replace(' ', '')
			keyname = key['name'].lower().replace(' ', '')
			if key['date'] == v[0] and (v1 in keyname or keyname in v1):
				cpto_name = path_cp + key['song'] + v[2]
				print 'copy [%s] to [%s]' % (k, cpto_name)
				rename_array.remove(key)
				finded = True
				break

		if False == finded:
			print '==== not rename!!! %s========' % (','.join(v))
			cpto_name = '%s%s_%s%s' % (path_cp, v[0], v[1], v[2])
			print 'copy [%s] to [%s]' % (k, cpto_name)

#		print cpto_name
#		if True == os.path.exists(cpto_name):
#			print '[%s] is exist, not need copy!' % cpto_name
#		else:
#			shutil.copyfile(k, cpto_name)

